// 导入数据库操作模块
const db = require('../sql/index')
// 在头部区域导入 bcryptjs 后，
// 即可使用 bcrypt.compareSync(提交的密码，数据库中的密码) 方法验证密码是否正确
// compareSync() 函数的返回值为布尔值，true 表示密码正确，false 表示密码错误
const bcrypt = require('bcryptjs')
// 导入配置文件
const config = require('../config')
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')
// 又拍云
const upyuns = require('upyun');
const fs = require('fs');
const FormData = require('form-data');
// const bucket = new upyuns.Bucket('sportqwe', '030306', 'MB3pbgMD5xoTYfV7hQFNMalvoNxNgdYb')
const bucket = new upyuns.Bucket('ydsports', 'sport', '3aTW7QCtkkA9z1Jcppqk0qASoRw8sQDZ')

const upyun = new upyuns.Client(bucket);
// const domain = 'http://sportqwe.test.upcdn.net/'
const domain = 'http://ydsports.test.upcdn.net/'



//查询个人信息
exports.wx_UserInfo = async (req, res) => {
    const open_id = await get_openid(req)
    console.log(open_id,'个扽');
    const sql = `select * from wx_users where open_id='${open_id}'`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取个人数据成功！',
            data: results,
        })
    })
}

// 更新用户基本信息的处理函数
exports.updatewx_UserInfo = (req, res) => {
    // console.log(get_openid(req));
    // console.log(req,'asdasdasdas');
    console.log(req);
    get_openid(req).then(id => {
    console.log(id,'asdasdasdas');

        const sql = `update wx_users set ? where open_id='${id}'`
        db.query(sql, req.body, (err, results) => {
            if (err) return res.send(err)
            // if (results.affectedRows == 1) {
                res.send({
                    status: 200,
                    message: '修改成功！',
                })
            // }
        })
    })
}
//获取token
async function get_openid(req) {
    const token = req.headers.authorization.replace("Bearer ", "");
    const secret_key = config.jwtSecretKey

    const { openid } = await util.jwt(token, secret_key)
    return openid
}
const util = {
    jwt(token, secret_key) {
        // console.log(7777,token,secret_key,8888);
        return new Promise((resolve, reject) => {
            jwt.verify(token, secret_key, (error, decoded) => {
                if (error) {
                    console.log(`传值有问题: ${error.message}`);
                    reject(error)
                }
                // console.log(decoded);
                resolve(decoded)
            })
        })
    }
}